<?php
/*
+--------------------------------------------------------------------------
|   Anwsion [#RELEASE_VERSION#]
|   ========================================
|   by Tatfook Network Team
|   (c) 2011 - 2012 Anwsion Software
|   http://www.anwsion.com
|   ========================================
|   Support: zhengqiang@gmail.com
|   
+---------------------------------------------------------------------------
*/

class c_main_class extends AWS_CONTROLLER
{
	var $versions = array();
	var $db_version = 0;
	
	public function get_access_rule()
	{
		$rule_action['rule_type'] = 'black';
		$rule_action['actions'] = array();
		
		return $rule_action;
	}

	public function setup()
	{
		@set_time_limit(0);
		
		// 升级程序禁止任何输入
		unset($_POST);
		
		define('ROOT_PATH', realpath(AWS_PATH . '../'));
		
		/*if (!is_dir(ROOT_PATH . '/install/db/upgrade/'))
		{
			H::redirect_msg('请上传最新版本的 install 目录.'));
		}*/
		
		if (!is_really_writable(AWS_PATH))
		{
			H::redirect_msg('目录 ' . AWS_PATH . ' 无法写入, 请修改目录权限');
		}
		
		$trash_files = array(
			ROOT_PATH . '/app/account/controller/c_login_class.inc.php',
			ROOT_PATH . '/app/account/controller/c_captcha_class.inc.php',
			ROOT_PATH . '/app/account/controller/c_register_class.inc.php',
			ROOT_PATH . '/app/account/controller/c_valid_class.inc.php',
			ROOT_PATH . '/app/account/controller/c_active_class.inc.php',
		);
		
		foreach ($trash_files AS $trash_file)
		{
			if (file_exists($trash_file))
			{
				if (!@unlink($trash_file))
				{
					$exists_trash_files[] = $trash_file;
				}
			}
		}

		if (is_array($exists_trash_files))
		{
			H::redirect_msg('老版本的一些文件已经不再使用, 请删除下列文件: <br />' . implode($exists_trash_files, '<br />'));
		}
		
		// 在此标记有 SQL 升级的版本号, 名称为上一个版本的 Build 编号
		$this->versions = array(
			20120608,
			20120615,
			20120622,
		);
		
		if (!$this->db_version = get_setting('db_version'))
		{
			$this->db_version = 20120608;
		}
		
		if (!in_array($this->db_version, $this->versions))
		{
			H::redirect_msg('您的程序已经是最新版本');
		}
		
		if (G_INDEX_SCRIPT)
		{
			TPL::assign('static_url', './static');
		}
		else
		{
			TPL::assign('static_url', '../static');
		}
	}
	
	public function index_action()
	{
		TPL::assign('db_version', $this->db_version);
		TPL::output('install/upgrade');
	}
	
	public function run_action()
	{
		foreach ($this->versions AS $version)
		{
			$sql_file = ROOT_PATH . '/app/upgrade/db/' . $version . '.sql';
			
			if ($this->db_version <= $version AND file_exists($sql_file))
			{	
				$sql_query .= file_get_contents($sql_file) . "\n";
			}
		}
		
		if (trim($sql_query))
		{
			$this->model('upgrade')->run_query($sql_query);
		}
		
		$this->model('setting')->set_vars(array(
			'db_version' => G_VERSION_BUILD
		));
		
		$this->model('setting')->update_setting_config();
		
		H::redirect_msg('升级完成, 您的程序已经是最新版本', get_setting('base_url'));
	}
}